package com.linkage.jz.bankruptcy.activity.Vote;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;

import org.greenrobot.eventbus.EventBus;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 显示或提交表决页面 show or edit
 */
public class ProVoteEditVoteActivity extends ProVoteBaseActivity {

    public static final int REQUEST_CODE_VOTE = 0x111f;
    private boolean fromSelf;//true 为本页面切换编辑和显示 false为从其他页面跳转过来

    private boolean vote;//true 为显示， false 编辑
    private String voteId;
    private String groupId;
    private boolean allowChange;

    private ImageButton titleBack;
    private TextView titleText;
    private Button titleMenu;

    //表决编辑元素
    private LinearLayout layoutVoteEdit;
    private TextView timeText;
    private RadioGroup radioGroup;
    private EditText editText;
    private TextView editTextLength;
    private int MAX_LENGTH = 200;//最大输入字符数200
    private int voteOpinion;//0不同意 1同意
    private String supplementOpinion;//补充意见

    //表决显示元素
    private LinearLayout layoutVoteInfo;
    private TextView myVoteResult;
    private TextView myVoteOpinion;
    private TextView textAllowChange;
    private Button btnAllowChange;

    @Override
    public void initView() {
        setContentView(R.layout.activity_pro_vote_edit_vote);
        layoutVoteEdit = findViewById(R.id.layout_vote_edit);
        timeText = findViewById(R.id.time);
        radioGroup = findViewById(R.id.rg_vote_type);
        editText = findViewById(R.id.et_vote_desc);
        editTextLength = findViewById(R.id.ed_vote_desc_length);

        layoutVoteInfo = findViewById(R.id.layout_vote_info);
        myVoteResult = findViewById(R.id.my_vote_result);
        myVoteOpinion = findViewById(R.id.my_vote_desc);
        textAllowChange = findViewById(R.id.txt_operate_change);
        btnAllowChange = findViewById(R.id.btn_operate_change);
    }

    @Override
    public void initData() {
        vote = getIntent().getBooleanExtra("vote", true);
        voteId = getIntent().getStringExtra("voteId");
        groupId = getIntent().getStringExtra("groupId");
        allowChange = getIntent().getBooleanExtra("allowChange", false);
        voteOpinion = getIntent().getIntExtra("voteOpinion", 0);
        supplementOpinion = getIntent().getStringExtra("supplementOpinion");

        titleBack = findViewById(R.id.title_back);
        titleBack.setVisibility(View.INVISIBLE);
        titleText = findViewById(R.id.title_text);
        titleMenu = findViewById(R.id.title_menu1);
        titleBack.setOnClickListener(this);
        titleText.setText("表决");
        showInfoOrEdit(vote);
    }

    private void showInfoOrEdit(boolean show) {
        if(show) {
            vote = true;
            titleBack.setVisibility(View.VISIBLE);
            titleMenu.setVisibility(View.INVISIBLE);
            layoutVoteEdit.setVisibility(View.GONE);
            layoutVoteInfo.setVisibility(View.VISIBLE);
            myVoteResult.setText(voteOpinion == 0 ? "不同意" : "同意");
            myVoteOpinion.setText(TextUtils.isEmpty(supplementOpinion) ? "无表决意见" : supplementOpinion);
            ProVote proVote = BundleUtils.getProVote();
            if(proVote.getStatus() == 2) {
                if(allowChange) {
                    textAllowChange.setVisibility(View.GONE);
                    btnAllowChange.setVisibility(View.VISIBLE);
                }else {
                    textAllowChange.setVisibility(View.VISIBLE);
                    btnAllowChange.setVisibility(View.GONE);
                }
            }else {
                textAllowChange.setVisibility(View.GONE);
                btnAllowChange.setVisibility(View.GONE);
            }
            btnAllowChange.setOnClickListener(this);
        }else {
            ProVote mProVote = BundleUtils.getProVote();
            titleMenu.setTextColor(getResources().getColor(R.color.color_289F9F));
            titleMenu.setVisibility(View.VISIBLE);
            layoutVoteEdit.setVisibility(View.VISIBLE);
            timeText.setText(getDatePoor(mProVote.getEndTime(), System.currentTimeMillis()));
            layoutVoteInfo.setVisibility(View.GONE);
        }
        titleMenu.setText("提交");
        titleMenu.setOnClickListener(this);
    }

    @Override
    public void setListener() {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > MAX_LENGTH){ //判断EditText中输入的字符数是不是已经大于6
                    editText.setText(s.toString().substring(0,MAX_LENGTH)); //设置EditText只显示前面6位字符
                    editText.setSelection(MAX_LENGTH);//让光标移至末端
                    ToastUtil.showShort("输入字数已达上限" + MAX_LENGTH + "个");
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextLength.setText(s.toString().length()+"/"+MAX_LENGTH);
            }
        });
    }

    @Override
    public void initTitle() {

    }

    private void submitVote() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showLoading();
        voteOpinion = radioGroup.getCheckedRadioButtonId() == R.id.rg_vote_type_1 ? 1 : 0;
        supplementOpinion = editText.getText().toString();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .getVoteSubmitVote_Creditor(userToken, voteId, groupId==null? "" : groupId, String.valueOf(voteOpinion), supplementOpinion)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_VOTE);
                        EventBus.getDefault().post(event);
                        LogUtil.e("--response--", json.toString());
                        if(fromSelf) {
                            showInfoOrEdit(true);
                        }else {
                            Intent intent = new Intent();
                            intent.putExtra("groupId", groupId);
                            intent.putExtra("voteOpinion", voteOpinion);
                            intent.putExtra("supplementOpinion", supplementOpinion);
                            intent.putExtra("allowChange", allowChange);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

    public static String getDatePoor(long endTime, long nowTime) {
        endTime = endTime * 1000;
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endTime - nowTime;
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.title_menu1:
                submitVote();
                break;
            case R.id.btn_operate_change:
                showInfoOrEdit(false);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
            if(vote)
            {
                finish();
            }
            return false;

        }
        return super.onKeyDown(keyCode, event);
    }
}
